const db = wx.cloud.database()      //获取数据库的引用
Page({
  data: {
    realname: "",
    files: [],     //图片临时地址
  },
  //打开相册，选择图片
  handleSelect(e) {
    // console.log(e)
    let arr = e.detail.tempFilePaths    //本地临时地址
    let files = arr.map(item => {
      return { url: item }
    })
    this.setData({
      files
    })

  },
  //点击上传
  handleUpload() {
    //显示提示框，防止重复提交
    wx.showLoading({
      title: '正在提交',
      mask: true
    })
    // 上传图片
    let filePath = this.data.files[0].url;
    let nowtime = new Date().getTime()
    let ext = filePath.split(".").pop()

    wx.cloud.uploadFile({
      cloudPath: nowtime + "." + ext,     //云端地址
      filePath: filePath,       //本地临时地址,
      success: res => {
        // console.log(res)
        let fileID = res.fileID;      //图片云端地址

        //添加数据库
        db.collection("users").add({
          data: { realname: this.data.realname, image: fileID }
        })
          .then(res => {
            //隐藏loading框
            wx.hideLoading()
          })
          .catch(err => {
            console.log(err)
          })


      }
    })
  }

})